package com.suneast.suneaststore.modules.personal;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.modules.main.event.GotCartCount;
import com.suneast.suneaststore.modules.personal.address.AddressListFragment;
import com.suneast.suneaststore.modules.personal.order.fragment.SaleManage;
import com.suneast.suneaststore.modules.personal.wallet.BalanceFragment;
import com.suneast.suneaststore.modules.personal.wallet.CoinFragment;
import com.suneast.suneaststore.modules.personal.wallet.TopUpFragment;
import com.suneast.suneaststore.modules.personal.wallet.WithdrawFragment;
import com.suneast.suneaststore.modules.personal.wallet.bankcard.BankCardListFragment;
import com.suneast.suneaststore.modules.personal.collect.CollectFragment;
import com.suneast.suneaststore.modules.personal.info.HeadImgFragment;
import com.suneast.suneaststore.modules.personal.info.SimpleAboutUsFragment;
import com.suneast.suneaststore.modules.personal.info.event.ChangeHeadImg;
import com.suneast.suneaststore.modules.personal.order.fragment.PurchaseManage;
import com.suneast.suneaststore.modules.personal.sign.SignInFragment;
import com.suneast.suneaststore.modules.personal.sign.event.ExitCurrentAccountEvent;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.personal.sign.event.ModifyPwdResult;
import com.suneast.suneaststore.modules.personal.sign.event.SignInResult;
import com.suneast.suneaststore.modules.personal.sign.event.SignUpResult;
import com.suneast.suneaststore.modules.personal.trace.TraceFragment;
import com.suneast.suneaststore.modules.personal.wallet.event.BalanceValueChange;
import com.suneast.suneaststore.modules.shopcart.ShopCartHandler;
import com.suneast.suneaststore.ui.fragments.bottom.BottomItemFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class PersonalFragment extends BottomItemFragment {

    @Override
    public @LayoutRes
    int setLayout() {
        return R.layout.fragment_personal;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @OnClick({R.id.user_icon_img, R.id.tv_account_balance, R.id.tiv_top_up,
            R.id.tiv_withdraw_deposit, R.id.tiv_bank_card, R.id.tiv_lianbang_coin, R.id.tv_all_order,
            R.id.tiv_goods_wait_pay, R.id.tiv_goods_wait_send, R.id.tiv_goods_wait_confirm,
            R.id.tiv_goods_wait_appraise, R.id.tiv_goods_after_sale, R.id.tv_merchant_all_order,
            R.id.tiv_merchant_goods_wait_pay, R.id.tiv_merchant_goods_wait_send,
            R.id.tiv_merchant_goods_arrived, R.id.tiv_merchant_goods_wait_appraise,
            R.id.tiv_my_qr_code, R.id.tiv_address_manager, R.id.tiv_my_collection, R.id.tiv_my_trace,
            R.id.tiv_about_us, R.id.tiv_my_rating, R.id.tiv_binding_record, R.id.tiv_app_settings})
    public void onViewClick(View view) {
        if (AccountManager.getSignState()) {
            switch (view.getId()) {
                case R.id.user_icon_img: {
                    getParentDelegate().start(new HeadImgFragment().withHeadImgUrl(headImgUrl));
                }
                break;
                case R.id.tv_account_balance: {
                    getParentDelegate().start(new BalanceFragment().withBalanceValue(balanceValue));
                }
                break;
                case R.id.tiv_top_up: {
                    getParentDelegate().start(new TopUpFragment().withBalanceValue(balanceValue));
                }
                break;
                case R.id.tiv_withdraw_deposit: {
                    if (AccountManager.getLevel() > 1) {
                        getParentDelegate().start(new WithdrawFragment()
                                .withBalanceValue(balanceValue).withGoodsValue(goodsValue));
                    } else {
                        getParentDelegate().start(new WithdrawFragment().withBalanceValue(balanceValue));
                    }
                }
                break;
                case R.id.tiv_bank_card: {
                    getParentDelegate().start(new BankCardListFragment());
                }
                break;
                case R.id.tiv_lianbang_coin: {
                    getParentDelegate().start(new CoinFragment().withCoinValue(coinValue));
                }
                break;
                case R.id.tv_all_order:
                case R.id.tiv_goods_wait_pay:
                case R.id.tiv_goods_wait_send:
                case R.id.tiv_goods_wait_confirm:
                case R.id.tiv_goods_wait_appraise:
                case R.id.tiv_goods_after_sale:
                    getParentDelegate().start(new PurchaseManage().withId(view.getId()));
                    break;
                case R.id.tv_merchant_all_order:
                case R.id.tiv_merchant_goods_wait_pay:
                case R.id.tiv_merchant_goods_wait_send:
                case R.id.tiv_merchant_goods_arrived:
                case R.id.tiv_merchant_goods_wait_appraise:
                    getParentDelegate().start(new SaleManage().withId(view.getId()));
                    break;
                case R.id.tiv_my_qr_code: {
                    //todo 显示我的二维码界面
                }
                break;
                case R.id.tiv_address_manager: {
                    getParentDelegate().start(new AddressListFragment());
                }
                break;
                case R.id.tiv_my_collection: {
                    getParentDelegate().start(new CollectFragment());
                }
                break;
                case R.id.tiv_my_trace: {
                    getParentDelegate().start(new TraceFragment());
                }
                break;
                case R.id.tiv_about_us: {
                    getParentDelegate().start(new SimpleAboutUsFragment());
                }
                break;
                case R.id.tiv_my_rating: {

                }
                break;
                case R.id.tiv_binding_record: {

                }
                break;
                case R.id.tiv_app_settings: {
                }
                break;
            }
        } else {
            getParentDelegate().start(new SignInFragment());
        }
    }

    @BindView(R.id.user_icon_img)
    CircleImageView imgUserIcon;

    @BindView(R.id.tv_user_name)
    TextView userNameTv;

    @BindView(R.id.tv_vip_flag)
    TextView vipFlagTv;

    @BindView(R.id.tv_account_balance)
    TextView accountBalanceTv;

    @BindView(R.id.layout_merchant_order_header)
    ConstraintLayout merchantOrderHeaderLayout;

    @BindView(R.id.layout_merchant_order)
    LinearLayout merchantOrderLayout;

    @BindView(R.id.line_merchant_middle)
    LinearLayoutCompat middleLine;
    @BindView(R.id.line_merchant_bottom)
    LinearLayoutCompat bottomLine;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        Log.e(TAG, "onLazyInitView: ");
        if (AccountManager.getSignState()) {
            // 请求用户数据
            PersonHandler.requestPersonInfo();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (accountBalanceTv != null) {
                accountBalanceTv.setText(new DecimalFormat("0.00").format(balanceValue));
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onExitCurrentAccount(ExitCurrentAccountEvent event) {
        setUIToUnSign();
        EventBus.getDefault().post(new GotCartCount(Flag.Result.FAILURE, 0));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSignInState(SignInResult event) {
        switch (event.getState()) {
            case Flag.Result.SUCCEED: {
                // 请求用户数据
                PersonHandler.requestPersonInfo();
            }
            break;
            case Flag.Result.FAILURE: {
            }
            break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSignUpResult(SignUpResult result) {
        if (result.getResult() == Flag.Result.SUCCEED) {
            // 请求用户数据
            PersonHandler.requestPersonInfo();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onModifyPwdResult(ModifyPwdResult result) {
        switch (result.getResult()) {
            case Flag.Result.SUCCEED: {
                setUIToUnSign();
            }
            break;
        }
    }

    public static double balanceValue;
    private double goodsValue;
    private String coinValue;
    private String headImgUrl = null;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotUserInfo(GotUserInfo event) {
        balanceValue = event.getBalance();
        goodsValue = event.getGoodsBalance();
        coinValue = event.getIntegral() != null && event.getIntegral().length() > 0 ?
                event.getIntegral() : "0.00";
        headImgUrl = event.getHeadImg();
        if (headImgUrl.length() > 0) {
            Glide.with(_mActivity).load(event.getHeadImg()).into(imgUserIcon);
        } else {
            imgUserIcon.setImageResource(R.drawable.ic_user_default);
        }
        if (event.getName().length() > 0) {
            userNameTv.setText(event.getName());
        } else {
            userNameTv.setText(event.getMobile());
        }
        DecimalFormat df = new DecimalFormat("0.00");
        accountBalanceTv.setText(df.format(event.getBalance()));
        if (event.getLevel() > 1) {
            merchantOrderHeaderLayout.setVisibility(View.VISIBLE);
            merchantOrderLayout.setVisibility(View.VISIBLE);
            middleLine.setVisibility(View.VISIBLE);
            bottomLine.setVisibility(View.VISIBLE);
            vipFlagTv.setText("经销商");
        } else {
            merchantOrderHeaderLayout.setVisibility(View.GONE);
            merchantOrderLayout.setVisibility(View.GONE);
            middleLine.setVisibility(View.GONE);
            bottomLine.setVisibility(View.GONE);
        }
        ShopCartHandler.requestCartCount();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChangeHeadImg(ChangeHeadImg event) {
        headImgUrl = event.getImgUrl();
        Glide.with(_mActivity).load(event.getImgUrl()).into(imgUserIcon);
    }

    private void setUIToUnSign() {
        imgUserIcon.setImageResource(R.drawable.ic_user_default);
        userNameTv.setText(getResources().getString(R.string.un_signed));
        accountBalanceTv.setText(getResources().getString(R.string.none_rmb));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBalanceValueChange(BalanceValueChange event) {
        if (accountBalanceTv != null) {
            accountBalanceTv.setText(new DecimalFormat("0.00").format(balanceValue));
        }
    }
}
